package com.appspot.urlheap.servlets;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.urlheap.data.Item;
import com.appspot.urlheap.data.PMF;

public class DeleteServlet extends BaseServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		super.doGet(req, resp);
		
		String pId = req.getParameter("id");
		if (pId == null) {
			resp.setContentType("text/html");
			resp.getWriter().println("error: missing id param");
			return;
		}
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Item item = pm.getObjectById(Item.class, new Long(pId));
			if (item != null && item.getUser().equals(getUser().getEmail())) {
				pm.deletePersistent(item);
			} else {
				resp.setContentType("text/html");
				resp.getWriter().println("error: can't delete item");
				return;
			}
		} finally {
			pm.close();
		}
		resp.sendRedirect("/index");
	}
}
